package org.restorator.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.restorator.entity.AnonymClientOrder;
import org.restorator.entity.Order;
import org.restorator.service.OrderService;
import org.restorator.service.impl.OrderServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import org.restorator.entity.Item;
import org.restorator.service.ItemService;
import org.restorator.service.impl.ItemServiceImpl;

import static org.restorator.utill.ControllerUtil.*;

/**
 * Controller for work with REST style requests on entity {@link Order} by it's id.
 *
 * @author Snisar Bogdan.
 */
@WebServlet(name = "orderController", urlPatterns = "/order/*")
public class OrderController extends HttpServlet {
    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());
    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String urlStringEnd = getUrlIdMatch(req, resp);
            Integer tableId = Integer.parseInt(urlStringEnd);
            logger.trace("Get request. Try fained  order by table id: {}", tableId);
            Order order = orderService.getOrderByTableId(tableId);

            if(order != null) {
                logger.trace("Order by table id is exist: {}", order);
                printOk(resp, orderService.toDto(order));
            }
            else{
                AnonymClientOrder entity = new AnonymClientOrder();
                orderService.save(entity, tableId);
                logger.trace("created new order : {}", entity);

                printOk(resp, orderService.toDto(entity));
            }
            
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack trace: {}", e.getMessage(), e);
            printError(resp);
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String urlStringEnd = getUrlIdMatch(req, resp);
            Integer orderId = Integer.parseInt(urlStringEnd);
            logger.trace("Try DELETE  item by id: {}", orderId);
            AnonymClientOrder entity = new AnonymClientOrder(); // bad way
            entity.setOrderId(orderId);
            orderService.delete(entity);

            printSuccess(resp.getWriter());
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. Stack : {}", e.getMessage(), e);
//            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    /*
    *  Получает tableId от клиента в body, для создание нового ордера для этого стола.
    *  Ответ "стандартнй" о новом оредере
    */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.trace("Get POST request");
        BufferedInputStream bf = new BufferedInputStream(req.getInputStream(), 1024*2);
        InputStreamReader reader = new InputStreamReader(bf, "UTF-8");

        StringBuilder builder = new StringBuilder();
        int value;
        while ((value = reader.read()) != -1) {
            builder.append((char) value);
        }
        String jsonBodyRequest = builder.toString();
        logger.debug("POST body information: {}", jsonBodyRequest);

    }


    /**
     * Used as update request for entity
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String urlStringEnd = getUrlIdMatch(req, resp);
            Integer orderId = Integer.parseInt(urlStringEnd);

            BufferedInputStream bf = new BufferedInputStream(req.getInputStream(), 1024*2);
            InputStreamReader reader = new InputStreamReader(bf, "UTF-8");

            StringBuilder builder = new StringBuilder();
            int value;
            while ((value = reader.read()) != -1) {
                builder.append((char) value);
            }
            String jsonBodyRequest = builder.toString();

            logger.debug("PUT body request: {}", jsonBodyRequest);
            Gson g = new Gson();


//            g.fromJson();


        } catch (Exception ex) {
            logger.error("Exception in doPut(): {}", ex);
        }
    }

}
